package hard滑动窗口最大值;

import java.util.*;

public class Solution {
    public int[] maxSlidingWindow2(int[] nums, int k) {
        int n = nums.length;
        if (n == 1){
            return nums;
        }
        int max = Integer.MIN_VALUE;
        int index = 0;
        int[] set = new int[n-k+1];

//        Queue<Integer> queue = new PriorityQueue<>((x, y) -> y - x);
        Queue<Integer> queue = new PriorityQueue<>(2,new Comparator<Integer>() {
            @Override
            public int compare(Integer o1, Integer o2) {
                if (o1 > o2)
                    return -1;
                else if (o1 < o2)
                    return 1;
                return 0;
            }
        });

        for (int i = 0; i < n; ) {
            if (queue.isEmpty()){
                for ( ; i < k; i++) {
                    queue.add(nums[i]);
                }
                set[index++] = queue.peek();
            }
            else{
                queue.remove(nums[i-k]);
                queue.add(nums[i]);
                set[index++] = queue.peek();
                i++;
            }
        }
        return set;
    }


    public int[] maxSlidingWindow(int[] nums, int k) {
        int n = nums.length;
        Deque<Integer> deque = new LinkedList<Integer>();
        for (int i = 0; i < k; ++i) {
            while (!deque.isEmpty() && nums[i] >= nums[deque.peekLast()]) {
                deque.pollLast();
            }
            deque.offerLast(i);
        }

        int[] ans = new int[n - k + 1];
        ans[0] = nums[deque.peekFirst()];
        for (int i = k; i < n; ++i) {
            while (!deque.isEmpty() && nums[i] >= nums[deque.peekLast()]) {
                deque.pollLast();
            }
            deque.offerLast(i);
            while (deque.peekFirst() <= i - k) {
                deque.pollFirst();
            }
            ans[i - k + 1] = nums[deque.peekFirst()];
        }
        return ans;
    }

    public int[] maxSlidingWindow1(int[] nums, int k) {
        int n = nums.length;
        PriorityQueue<int[]> pq = new PriorityQueue<int[]>(new Comparator<int[]>() {
            public int compare(int[] pair1, int[] pair2) {
                return pair1[0] != pair2[0] ? pair2[0] - pair1[0] : pair2[1] - pair1[1];
            }
        });
        for (int i = 0; i < k; ++i) {
            pq.offer(new int[]{nums[i], i});
        }
        int[] ans = new int[n - k + 1];
        ans[0] = pq.peek()[0];
        for (int i = k; i < n; ++i) {
            pq.offer(new int[]{nums[i], i});
            while (pq.peek()[1] <= i - k) {
                pq.poll();
            }
            ans[i - k + 1] = pq.peek()[0];
        }
        return ans;
    }
}
